package com.longyi.admin.service.impl;

import com.longyi.admin.entity.ChartPie;
import com.longyi.admin.entity.Menu;
import com.longyi.admin.entity.User;
import com.longyi.admin.mapper.MenuMapper;
import com.longyi.admin.mapper.UserMapper;
import com.longyi.admin.service.MenuService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
* MenuServiceImpl 服务实现类
*
* @author 龙毅
* @since 2025-09-08
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

@Resource
private MenuMapper menuMapper;

    @Override
public IPage PageList(IPage<Menu> page, Wrapper wrapper) {
    return menuMapper.PageList(page,wrapper);
    }

    @Override
    public List<Menu> getUserMenu(User user,List<Long> menuIds) {

        List<Menu> menuList=new ArrayList<>();
        for(Long menuId:menuIds){
            Menu menu=menuMapper.selectById(menuId);
            if(menu.getType()!=2) {
                menuList.add(menu);
            }
        }
        System.out.println(menuList);
        return  buildTreeMenu(menuList);
    }

    @Override
    public List<ChartPie> getMenuType() {
        return menuMapper.getMenuType();
    }

    @Override
    public List<Menu> tree(List<Menu> list) {

        return buildTreeMenu(list);
    }

    private List<Menu> buildTreeMenu(List<Menu> menuList) {
        List<Menu> treeMenuList=new ArrayList<>();

        for (Menu menu:menuList){
            if(menu.getParentId()==0){
                treeMenuList.add(menu);
            }
        }
//        构造子菜单
        for (Menu menu:treeMenuList){
            setChildren(menu,menuList);
        }
        treeMenuList.sort(Comparator.comparing(Menu::getOrderNum));
        for (Menu menu:treeMenuList){
            sortChildren(menu);
        }
        return treeMenuList;
    }

    private void sortChildren(Menu menu) {
        if(menu.getChildren()!=null){
            menu.getChildren().sort(Comparator.comparing(Menu::getOrderNum));
            for (Menu menu1:menu.getChildren()){

                sortChildren(menu1);
            }
        }
    }

    private void setChildren(Menu menu, List<Menu> menuList) {
        List<Menu> children=new ArrayList<>();
        for (Menu menu1:menuList){
            if(menu.getId().equals(menu1.getParentId())){
                        children.add(menu1);
                        setChildren(menu1,menuList);

            }

        }
        menu.setChildren(children);
    }


}
